<template>
  <div class="myContainer">
    <el-row class="myTitleBorderBottom">
      <el-col :span="12" class="myLineHeight_40px">{{title}}</el-col>
      <el-col :span="12" class="myTextAlignRight">
        <el-button type="primary" class="myBgGreen" @click="onChart">{{buttonText}}</el-button>
      </el-col>
    </el-row>
    <el-row class="myMarginTop_10px" :gutter="10">
      <el-col :span="3">
        <template>
          <el-select 
            v-model="hierarchyValue"
            @change="changeLevel"
            placeholder="层级">
            <el-option
              v-for="item in hierarchyList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3">
        <template>
          <el-select
            v-model="regionValue"
            multiple
            collapse-tags
            class="mySelect"
            placeholder="区域">
            <el-option
              v-for="item in regionList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3">
        <template>
          <el-select 
            v-model="planValue"
            filterable
            placeholder="全部计划">
            <el-option
              v-for="item in planList"
              :key="item.plan_id"
              :label="item.plan_title"
              :value="item.plan_id">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3">
        <template>
          <el-select v-model="typeValue"
            filterable
            placeholder="全部考核类型">
            <el-option
              v-for="item in typeList"
              :key="item.type_name"
              :label="item.type_name"
              :value="item.type_id">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="time"
          type="daterange"
          :clearable=false
          :editable=false
          align="left" 
          unlink-panels
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期" 
          :picker-options="timeOptions">
        </el-date-picker> 
      </el-col>
      <el-col :span="3">
        <el-button type="primary" class="myBgGreen" @click="onSearch">查 询</el-button>
      </el-col>
    </el-row>
    <el-row class="myMarginTop_10px">
      <el-col :span="24">
        <el-table
          v-if="isChart"
          ref="multipleTable"
          :data="list"
          :border = true
          :stripe = true
          v-loading="loading"
          style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item :label="item.region+':'" v-for="item in props.row.details">
                  <span>{{ item.score.toFixed(2) }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="60">
          </el-table-column>
          <el-table-column
            prop="date"
            label="截止时间"
            width="180">
          </el-table-column>
          <el-table-column
            prop="regions"
            label="区域">
            <template scope="scope">
              <span class="myTabTitle">{{scope.row.regions}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="score_avg"
            label="平均分"
            width="150">
            <template scope="scope">
              <span>{{scope.row.score_avg.toFixed(2)}}</span>
            </template>
          </el-table-column> 
        </el-table>
        <vue-highcharts v-else :Highcharts="Highcharts" :options="option" ref="visitorChart" style="height: 600px"></vue-highcharts>
      </el-col>
    </el-row>
  </div>
</template>

<style>
  .mySelect .el-input__inner,.mySelect .el-select__tags{
    height: 40px !important;
    overflow: hidden;
  }
  .mySelect.el-select .el-tag{
    margin: 8px 0 3px 6px !important;
  }
</style>
<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myTitleBorderBottom{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    border-bottom: 1px solid #dbdbdb;
    padding-bottom: 5px;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top:2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myMarginTop_10px{
    margin-top: 10px;
  }
  .myColorRed{
    color: #f00;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    /*width: 90px;*/
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    /*width: 50%;*/
  }
  .myTabTitle{
    display: -webkit-box;
    /*! autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
    -webkit-line-clamp: 1;
    overflow: hidden;
  }
</style>

<script>
    import VueHighcharts from 'vue2-highcharts';
    import Highcharts from  "highcharts";  
    import { getPlanList , getTypeList , getAverage } from "@/api/quality";
    import { getLevelArea } from "@/api/area";
    export default {
    data(){
        return{  
          title:"得分情况",   
          loading:false,
          hierarchyValue:1,
          hierarchyList:[
            {value:1,label:"集团"},
            {value:2,label:"片区"},
            {value:3,label:"小区"},
          ],
          regionValue:[],
          regionList:[],
          planValue:"",
          planList:[],
          typeValue:"",
          typeList:[],

          regionOptions: [],
          regionOptSelected: [],
          list:[],
          isChart:true,
          buttonText:'图表',
          time:[],
          timeOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
            shortcuts: [{
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
                picker.$emit('pick', [start, end]);
              }
            }]
          },
          Highcharts: Highcharts,
          option:{
            chart: {
                zoomType: ''
            },
            title: {
                text: '得分情况统计'
            },
            subtitle: {
                text: ''
            },
            credits:{
                  enabled: false  
            },
            colors:[
                '#ffa92e',
                '#00c2a9',
                '#2eb3ff',
                '#5db0eb',
                '#d87c7a',
                '#8698b5'
            ],
            xAxis: [
                {
                  categories: [],
                  crosshair: true
                }
            ],
            yAxis: [{ 
                title: {
                    text: '得分',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                },
                labels: {
                    format: '{value}分',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                },
              }],
            tooltip: {
                shared: true
            },
            series: [],
          }
      }
    },
    created() {
        document.title=this.title; 
        this.time=[this.GMTToStr(new Date(new Date().getTime() - 3600 * 1000 * 24 * 29)),this.GMTToStr(new Date())];
        this.changeLevel(1);//区域
    },
    computed: { 
    },
    components: {
      VueHighcharts 
    },
    methods:{
      GMTToStr(time){
        let date = new Date(time)
        let Str=date.getFullYear() + '-' +
        (date.getMonth() + 1) + '-' + 
        date.getDate() 
        //+ ' ' + 
        // date.getHours() + ':' + 
        // date.getMinutes() + ':' + 
        // date.getSeconds()
        return Str
      },
      changeLevel(val){
        let vm=this;
        let params={
          level:val
        }
        getLevelArea(params).then(response => {
          let res=response.data;
          vm.regionList=res;
          if(res.length>0){
            vm.regionValue=[res[0].value];
          }

          vm.ongetPlanList();//计划列表
          
        }).catch(error => {
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      ongetPlanList(){
        let vm=this;
        let params={
          page_num:1,
          page_size:10000
        }
        getPlanList(params).then(response => {
          let res=response.data;
          vm.planList=res.rows;
          vm.planValue=res.rows[0].plan_id||'';

          vm.ongetTypeList();

        }).catch(error => {
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      ongetTypeList(){
        let vm=this;
        let params={ 
          page_num:1,
          page_size:10000
        } 
        getTypeList(params).then(response => {
          let res=response.data;
          vm.typeList=res.rows;
          vm.typeValue=res.rows[0].type_id||''; 

          vm.ongetAverage();

        }).catch(error => { 
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      ongetAverage(){
        let vm=this;
        if(vm.regionValue.length==0){
          vm.$message.info("区域不能为空！");
          return;
        }
        let params={
          plan_id:vm.planValue,
          type_id:vm.typeValue,
          level:vm.hierarchyValue,
          region:vm.regionValue.toString(),
          start_time:vm.time?vm.time[0]:'',
          end_time:vm.time?vm.time[1]:'',
        }
        vm.loading=true;
        getAverage(params).then(response => {
          let res=response.data;
          vm.list=res;
          !vm.isChart?setTimeout(function(){vm.onSetChartData()},100):'';
          vm.loading=false;
        }).catch(error => {
          vm.loading=false;
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      onSearch(){
        this.ongetAverage();        
      },
      onChart(){
        let vm=this;
        vm.isChart=!vm.isChart;
        if(vm.isChart){
            vm.buttonText='图表'
        }else{
          vm.buttonText='表格'
          setTimeout(function(){vm.onSetChartData()},100);
        }
      },
      onSetChartData(){
        let vm=this,lengthNum=vm.list.length;
        let xAxisList=new Array(lengthNum);//横坐标描述
        let score_avg=new Array(lengthNum);//平均分
        let areas=[];//区域
        let datas={};//区域数据集
        let visitorChart = vm.$refs.visitorChart;
        if(visitorChart.getChart().series.length){
          for(let i=0; i<visitorChart.getChart().series.length; ){
            visitorChart.getChart().series[0].remove();
          }
        }
        for(let i=0; i<lengthNum; i++){
          xAxisList[i]=vm.list[i].date;
          score_avg[i]=Number(vm.list[i].score_avg.toFixed(2));
        }
        visitorChart.getChart().xAxis[0].setCategories(xAxisList);
        if(lengthNum>0){
          areas=vm.list[0].regions.split(",");
          for(let i=0; i<vm.list[0].details.length; i++){
            datas[i]=[];
          }
          for(let i=0; i<lengthNum; i++){
            for(let j=0; j<vm.list[i].details.length; j++){
              datas[j].push(Number(vm.list[i].details[j].score.toFixed(2)));
            }
          }
          visitorChart.getChart().addSeries(
            {
              name: '平均分',
              type: 'spline',
              yAxis: 0,
              data: score_avg,
              tooltip: {
                  valueSuffix: '分'
              }
            }
          )
          for(let i=0; i<areas.length; i++){
            visitorChart.getChart().addSeries({
              name: areas[i],
              type: 'spline',
              yAxis: 0,
              data: datas[i],
              tooltip: {
                valueSuffix: '分'
              }
            })
          }
        }
      },
      
    }
  }


</script>



